<template>
  <div class="time-range-selector">
    <div class="section-header">
      <el-icon class="section-icon"><Clock /></el-icon>
      <span class="section-title">时间范围</span>
    </div>
    
    <div class="time-content">
      <!-- 快速选择按钮 -->
      <div class="quick-select">
        <el-button size="small" @click="setDefault">默认范围</el-button>
        <el-button size="small" @click="setToday">今天</el-button>
        <el-button size="small" @click="setThisWeek">本周</el-button>
        <el-button size="small" @click="setNextWeek">下周</el-button>
        <el-button size="small" @click="setThisMonth">本月</el-button>
      </div>
      
      <!-- 日期选择器 -->
      <div class="date-pickers">
        <div class="date-item">
          <label class="date-label">开始日期</label>
          <el-date-picker
            v-model="startDate"
            type="date"
            placeholder="选择开始日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleStartDateChange"
            class="date-picker"
          />
        </div>
        
        <div class="date-item">
          <label class="date-label">结束日期</label>
          <el-date-picker
            v-model="endDate"
            type="date"
            placeholder="选择结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleEndDateChange"
            class="date-picker"
          />
        </div>
      </div>
      
      <!-- 时间范围显示 -->
      <div class="time-summary" v-if="startDate && endDate">
        <el-tag type="success" size="small">
          {{ formatDateRange() }}
        </el-tag>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { Clock } from '@element-plus/icons-vue'

// Props
const props = defineProps({
  startTime: {
    type: Date,
    default: null
  },
  endTime: {
    type: Date,
    default: null
  }
})

// Emits
const emit = defineEmits(['update:startTime', 'update:endTime'])

// 响应式数据
const startDate = ref('')
const endDate = ref('')

// 计算属性
const startDateTime = computed(() => {
  if (!startDate.value) return null
  const date = new Date(startDate.value)
  date.setHours(0, 0, 0, 0)
  return date
})

const endDateTime = computed(() => {
  if (!endDate.value) return null
  const date = new Date(endDate.value)
  date.setHours(23, 59, 59, 999)
  return date
})

// 监听计算属性变化，向父组件发送更新
watch(startDateTime, (newVal) => {
  emit('update:startTime', newVal)
})

watch(endDateTime, (newVal) => {
  emit('update:endTime', newVal)
})

// 监听外部传入的时间变化
watch(() => props.startTime, (newVal) => {
  if (newVal) {
    startDate.value = formatDateToString(newVal)
  }
}, { immediate: true })

watch(() => props.endTime, (newVal) => {
  if (newVal) {
    endDate.value = formatDateToString(newVal)
  }
}, { immediate: true })

// 处理日期变化
const handleStartDateChange = (value) => {
  startDate.value = value
}

const handleEndDateChange = (value) => {
  endDate.value = value
}

// 格式化日期为字符串
const formatDateToString = (date) => {
  if (!date) return ''
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 获取今天0点的日期
const getTodayStart = () => {
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  return today
}

// 快速选择功能
const setDefault = () => {
  // 设置默认时间范围：今天0点前后6天
  const today = getTodayStart()
  const startDefault = new Date(today)
  startDefault.setDate(today.getDate() - 6)
  
  const endDefault = new Date(today)
  endDefault.setDate(today.getDate() + 6)
  
  startDate.value = formatDateToString(startDefault)
  endDate.value = formatDateToString(endDefault)
}

const setToday = () => {
  const today = getTodayStart()
  const tomorrow = new Date(today)
  tomorrow.setDate(tomorrow.getDate() + 1)
  
  startDate.value = formatDateToString(today)
  endDate.value = formatDateToString(today)
}

const setThisWeek = () => {
  const today = getTodayStart()
  const dayOfWeek = today.getDay()
  const startOfWeek = new Date(today)
  startOfWeek.setDate(today.getDate() - dayOfWeek)
  
  const endOfWeek = new Date(startOfWeek)
  endOfWeek.setDate(startOfWeek.getDate() + 6)
  
  startDate.value = formatDateToString(startOfWeek)
  endDate.value = formatDateToString(endOfWeek)
}

const setNextWeek = () => {
  const today = getTodayStart()
  const dayOfWeek = today.getDay()
  const startOfNextWeek = new Date(today)
  startOfNextWeek.setDate(today.getDate() + (7 - dayOfWeek))
  
  const endOfNextWeek = new Date(startOfNextWeek)
  endOfNextWeek.setDate(startOfNextWeek.getDate() + 6)
  
  startDate.value = formatDateToString(startOfNextWeek)
  endDate.value = formatDateToString(endOfNextWeek)
}

const setThisMonth = () => {
  const today = getTodayStart()
  const startOfMonth = new Date(today.getFullYear(), today.getMonth(), 1)
  const endOfMonth = new Date(today.getFullYear(), today.getMonth() + 1, 0)
  
  startDate.value = formatDateToString(startOfMonth)
  endDate.value = formatDateToString(endOfMonth)
}

// 格式化日期范围显示
const formatDateRange = () => {
  if (!startDate.value || !endDate.value) return ''
  
  const start = new Date(startDate.value)
  const end = new Date(endDate.value)
  const diffTime = Math.abs(end - start)
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 1
  
  return `${startDate.value} 至 ${endDate.value} (${diffDays}天)`
}

// 组件挂载时设置默认值
onMounted(() => {
  if (!props.startTime && !props.endTime) {
    // 设置默认时间范围：今天0点前后6天
    const today = getTodayStart()
    const startDefault = new Date(today)
    startDefault.setDate(today.getDate() - 6)
    
    const endDefault = new Date(today)
    endDefault.setDate(today.getDate() + 6)
    
    startDate.value = formatDateToString(startDefault)
    endDate.value = formatDateToString(endDefault)
  }
})
</script>

<style scoped>
.time-range-selector {
  margin-bottom: 24px;
}

.section-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.section-icon {
  color: #409eff;
  font-size: 18px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #ffffff;
}

.time-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.quick-select {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.date-pickers {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.date-item {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.date-label {
  font-size: 14px;
  color: #ccc;
  font-weight: 500;
}

.date-picker {
  width: 100%;
}

.time-summary {
  text-align: center;
  padding-top: 8px;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

/* Element Plus 日期选择器暗黑主题适配 */
:deep(.el-input__wrapper) {
  background-color: rgba(0, 0, 0, 0.3);
  border-color: rgba(255, 255, 255, 0.2);
}

:deep(.el-input__wrapper:hover) {
  border-color: #409eff;
}

:deep(.el-input__wrapper.is-focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

:deep(.el-input__inner) {
  color: #ffffff;
}

:deep(.el-input__inner::placeholder) {
  color: #999;
}
</style>
